/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package es.midiendoelsoftware.qaMetrics.test.acceptance;

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.SeleneseTestBase;
import com.thoughtworks.selenium.Selenium;
import es.midiendoelsoftware.qaMetrics.test.beans.Visualizer;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.StringTokenizer;
import static java.text.MessageFormat.format;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import org.concordion.internal.ConcordionBuilder;
import org.junit.AfterClass;
import org.junit.Test;
import org.openqa.selenium.server.SeleniumServer;

/**
 *
 * @author carlosg
 */
public class QAMetrics {

    private static Selenium selenium = null;
    private static SeleniumServer seleniumServer = null;
    /*@BeforeClass
    public static void setUpOnce() throws Throwable {
    //firefox,googlechrome
    selenium = new DefaultSelenium("localhost", 4444, "*googlechrome",
    "http://localhost:8080");
    seleniumServer = new SeleniumServer();
    seleniumServer.start();
    selenium.start();
    selenium.setSpeed("1000");
    }*/

    @AfterClass
    public static void tearDownOnce() {
        stopSelenium();

    }

    @Test
    public void test() throws IOException {
        new ConcordionBuilder().build().process(this).assertIsSatisfied();
    }

    private static void startSelenium(String aBrowser) throws Exception {
        //firefox,googlechrome
        selenium = new DefaultSelenium("localhost", 4444, "*" + aBrowser,
                "http://localhost:8080");
        seleniumServer = new SeleniumServer();
        seleniumServer.start();
        selenium.start();
        selenium.setSpeed("0");
    }

    private static void stopSelenium() {
        if (selenium != null) {
            selenium.stop();
            selenium = null;
        }
        if (seleniumServer != null) {
            seleniumServer.stop();
            seleniumServer = null;
        }
    }

    private void verify(String expected, String aText) {
        SeleneseTestBase.assertEquals(expected.trim(), selenium.getText(aText).trim());
    }

    private static String getFileMetrics(String aFileMetrics) throws IOException {
        byte metricsByte[] = new byte[65535];
        InputStream inputFile = null;
        String jsonMetrics = new String(metricsByte);
        try {
            inputFile = (new URL(aFileMetrics)).openConnection().getInputStream();
        } catch (MalformedURLException mURLExc) {
            //isn`t an URL. try to classloader
            inputFile = QAMetrics.class.getClassLoader().getResourceAsStream(aFileMetrics);
        }
        inputFile.read(metricsByte);
        return new String(metricsByte);
    }

    public static Visualizer getMetrics(String aFileMetrics) throws IOException {
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setRootClass(Visualizer.class);
        JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(getFileMetrics(aFileMetrics));
        return (Visualizer) JSONSerializer.toJava(jsonObject, jsonConfig);
    }

    public String qaMetrics(String visualizer, String hudsonUrl, String fileMetrics, String compatibleBrowsers, String languages) throws IOException, Exception {
        final StringTokenizer stTokenizer = new StringTokenizer(compatibleBrowsers, ",");
        do {
            startSelenium(stTokenizer.nextToken());
            selenium.open("/qaMetrics/" + visualizer);
            selenium.waitForPageToLoad("3000");
            //obtain metrics
            final Visualizer metrics = getMetrics(fileMetrics);
            //doing the tests
            for (int i = 0; i < metrics.getSections().length; i++) {
                // Comprobando que existe el título de la sección
                verify(metrics.getSections()[i].getTitle()[0], format("//x:h2[{0}]", i + 2));
                // Comprobando la descripción
                verify(metrics.getSections()[i].getDescription()[0], format("//x:p[{0}]", i + 2));
                //Comprobando las cabeceras
                for (int j = 0; j < metrics.getSections()[i].getMetrics().length; j++) {
                    if (j == 0) { //Es el primer campo de la sección (siempre es fecha);
                        verify("Fecha", format("//x:table[@id=''styling-custom-striping{0}'']/x:thead/x:tr/x:th[1]", i + 1));
                    }
                    verify(metrics.getSections()[i].getMetrics()[j].getHead()[0], format("//x:table[@id=''styling-custom-striping{0}'']/x:thead/x:tr/x:th[{1}]", i + 1, j + 1));
                }
            }
            stopSelenium();
        } while (stTokenizer.hasMoreTokens());
        return "correcta";
    }
}
